#-*- codeing = utf-8 -*-
#@Time : 2020/9/17 14:23
#@Author : 阳某
#@File : 淘宝登录.py
#@Software : PyCharm
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time

# 判断元素是否存在
def is_element_exist(self, element):
    try:
        self.find_element_by_xpath(element)
        return True
    except:
        return False
if __name__ == '__main__':
    options = webdriver.ChromeOptions()
    # 设置为开发者模式，防止网站识别
    options.add_experimental_option(
        'excludeSwitches', ['enable-automation'])
    # 加载驱动程序
    browser = webdriver.Chrome(options=options)
    # 窗口最大化
    browser.maximize_window()
    # 进入淘宝登陆页
    browser.get('https://login.taobao.com/member/login.jhtml')
    # 点击使用账号密码登陆
    try:
        browser.find_element_by_xpath('//*[@id="J_QRCodeLogin"]/div[5]/a[1]').click()
    except:
        pass
    browser.find_element_by_id("TPL_username_1").clear()
    browser.find_element_by_id("TPL_password_1").clear()
    # 填入账号密码
    browser.find_element_by_xpath('//*[@id="fm-login-id"]').send_keys('tb480426989')
    browser.find_element_by_class_name("pwd-field").click()
    browser.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys('xxxxx')
    time.sleep(1)
    # 点击登陆
    browser.find_element_by_id("J_SubmitStatic").click()
    # 判断是否出现滑块
    while True:
        if is_element_exist(browser, "//div[@class='site-nav-user']"):
            print("登陆成功")
            break
        else:
            time.sleep(2)
            if is_element_exist(browser, "//div[@id='nocaptcha']/div/span/a"):
                print("刷新滑块")
                browser.find_element_by_xpath("//div[@id='nocaptcha']/div/span/a").click()
                time.sleep(1)
                browser.find_element_by_id("TPL_password_1").clear()
                browser.find_element_by_class_name("pwd-field").click()
                browser.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys('xxxxx')
                browser.find_element_by_xpath("//span[@id='nc_1_n1z']").click()
                source = browser.find_element_by_id("nc_1_n1t")
                ActionChains(browser).drag_and_drop_by_offset(source, 258, 0).perform()
                browser.find_element_by_id("J_SubmitStatic").click()
            else:
                print("拉动滑块")
                browser.find_element_by_id("TPL_password_1").clear()
                browser.find_element_by_class_name("pwd-field").click()
                browser.find_element_by_xpath('//*[@id="fm-login-password"]').send_keys('xxxxx')
                time.sleep(1)
                browser.find_element_by_xpath("//span[@id='nc_1_n1z']").click()
                # 定位滑块元素
                source = browser.find_element_by_id("nc_1_n1t")
                # 定义鼠标拖放动作
                ActionChains(browser).drag_and_drop_by_offset(source, 258, 0).perform()
                browser.find_element_by_id("J_SubmitStatic").click()